﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Security.Principal;
using ChapterX.BusinessFacade;
using ChapterX.Common;

namespace ChapterX
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            StatisticSystem.LogAccess(Request.UserHostAddress, Request.UserAgent);
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            FormsAuthenticationTicket authTicket = AuthManager.AuthTicket;
            if (null == authTicket)
            {
                // Cookie failed to decrypt.
                return;
            }

            // When the ticket was created, the UserData property was assigned a
            // pipe delimited string of role names.
            string[] roles = authTicket.UserData.Split(new char[] { '|' });

            // Create an Identity object.
            FormsIdentity id = new FormsIdentity(authTicket);
            // This principal will flow throughout the request.
            GenericPrincipal principal = new GenericPrincipal(id, roles);
            // Attach the new principal object to the current HttpContext object.
            Context.User = principal;
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            //if (!Request.UserHostAddress.Equals("127.0.0.1"))
            {
                Exception ex = Server.GetLastError();

                if (ex is HttpRequestValidationException)
                {
                    Response.Redirect(String.Format("~/Errors/RequestError.aspx?ReturnUrl={0}",
                        HttpUtility.UrlEncode(Context.Request.Path)));
                    return;
                }
            }
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}